##coding:utf8
import os,sys,json,codecs
from collections import OrderedDict,Counter
import glob
import re
os.chdir(u'F:\\2018\\小米样例工具')

txt_lst = glob.glob('data_didi\\*.txt')
wav_lst = glob.glob('data_didi\\*.wav')


def strip_bracket(str_data):
    time = str_data.strip('[').rstrip(']')
    return [float(t) for t in time.split(',')]

def mk_dir(path):
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        pass

def read_file(path):
    return [line.strip().split('\t') for line in open(path)]

def cread_dict(lst,default='.wav'):
    lst_dict = OrderedDict()
    for s in lst:
        s_name = s.split('\\')[-1].replace(default,'.wav')
        lst_dict[s_name] = s
    return lst_dict

def sox_cut(wav,new_wav,start,end):
    cmd = ('sox %s %s trim %s %s ' % (wav, new_wav, start, end - start))
    os.system(cmd)

def main():
    t_dict = cread_dict(txt_lst,'.txt')
    w_dict = cread_dict(wav_lst)
    print(w_dict.items()[:])
    print(t_dict.items()[:])

    for t_name,t_text in t_dict.items():
        if w_dict.has_key(t_name):
            wav_dir = 'didi_out/wav/'+t_name.strip('.wav')
            mk_dir(wav_dir)
            new_lst = []
            contents = read_file(t_text)
            for index,con in enumerate(contents):
                start, end = strip_bracket(con[0])
                text = con[-1].decode('utf8')

                ########对文本进行判断是否是噪音或者噪音符号，如果是则前后不进行缩放 是且的关系,缩放关系如果间隔大于0.4，前后缩放0.2，如果小于0.4则取差值缩放一半###########

                if index < len(contents)-1:
                    tag = contents[index+1][-1].decode('utf8')
                    back_start, back_end = strip_bracket(contents[index+1][0])
                    if text != u'+' and (len(re.findall(u'\[.*?\]',text)) == 0):
                        if tag == u'+' or (len(re.findall(u'\[.*?\]',tag))) > 0 :
                            new_lst.append([str(start), str(end), "\t".join(con[2:])])
                        else:
                            if back_start - end >= 0.4:
                                end = end+0.2
                                contents[index+1][0] = '['+str(back_start-0.2)+','+str(back_end)+']'
                                new_lst.append([str(start), str(end), "\t".join(con[2:])])
                            else:
                                avage = (back_start-end)/2
                                end = end+avage
                                contents[index + 1][0] = '[' + str(back_start - avage) + ',' + str(back_end) + ']'
                                new_lst.append([str(start), str(end), "\t".join(con[2:])])

                    else:
                        new_lst.append([str(start), str(end), "\t".join(con[2:])])

                else:
                    new_lst.append([str(start), str(end), "\t".join(con[2:])])

                #print(start,end)
                sox_cut(w_dict[t_name], wav_dir + '/' + str(index).zfill(4) + '.wav', start, end)

            with open('didi_out/'+t_name.replace('.wav','.txt'),'w') as f:
                for ss in new_lst:

                    template = '['+ss[0]+','+ss[1]+']'+'\t'+ss[2]
                    f.write(template + '\n')

if __name__ == '__main__':
	main()







